import fileSaver from "file-saver";
import DataType from "utils/DataType";

const ResourceUtils = {
	// FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom })
	//保存到json文件
	download(data = {}, fileName) {
		fileSaver.saveAs(new Blob([JSON.stringify(data)], {type: "application/json;charset=utf-8"}), fileName);
	},
	downloadBlob(data = {}, fileName, fileType) {
		fileSaver.saveAs(new Blob([JSON.stringify(data)], fileType), fileName);
	},
	//保存到blob文本
	downloadText(data = {}, fileName) {
		fileSaver.saveAs(new Blob([JSON.stringify(data)], {type: "text/plain;charset=utf-8"}), fileName);
	},
	//保存文件流
	downloadStream(url, fileName) {
		fileSaver.saveAs(url, fileName);
	},
	//保存图片
	downloadCanvas(canvas, fileName) {
		canvas.toBlob((blob) => {
			fileSaver.saveAs(blob, fileName);
		}, "image/png");
	},
	//保存纯文件
	// Note: Ie and Edge don't support the new File constructor,
	// so it's better to construct blobs and use saveAs(blob, filename)
	downloadFile(data = {}, fileName) {
		fileSaver.saveAs(new File([JSON.stringify(data)], fileName, {type: "text/plain;charset=utf-8"}));
	},
	removeInvalid(params) {
		let datas = {};
		//去除无效数据
		Object.keys(params).forEach(key => {
			if (DataType.hasNotNullKey(params, key)) {
				if (key.toLowerCase().indexOf("width") !== -1 && params[key].toString().indexOf("px") === -1) {
					datas[key] = Number(params[key]);
				} else {
					datas[key] = params[key];
				}
			}
		});
		return datas;
	}
};

export default ResourceUtils;
